<template>
    <view class="container">
        <uni-segmented-control :current="currentIndex" :values="items" style-type="text" active-color="#007aff"
            @clickItem="onClickItem" />
        <view v-if="currentIndex === 0">
            <view style="padding-top: 10px;"></view>
            <uni-forms ref="baseForm" :modelValue="liuzhuanForm" labelPosition="left" border labelWidth="100px">
                <view style="padding-top: 10px;"></view>
                <uni-forms-item label="值班人" required>
                    <uni-row v-if="attenders.length != 0">
                        <uni-col :span="8" v-for="(item, idx) in attenders" :key="idx">
                            <view class="user-bg">
                                <text>{{ item.name }}</text>
                            </view>
                        </uni-col>
                    </uni-row>
                    <button @click="clickSelectAttender" class="btn-add">添加值班人</button>
                </uni-forms-item>
                <uni-forms-item label="值班日期" required>
                    <uni-datetime-picker @click="chuanci()" @change="chuanci2" @maskClick="chuanci2()" type="date"
                        return-type="string" v-model="liuzhuanForm.watchTime" />
                </uni-forms-item>
                <uni-forms-item label="交班人" required>
                    <uni-row v-if="attenders1.length != 0">
                        <uni-col :span="8" v-for="(item, idx) in attenders1" :key="idx">
                            <view class="user-bg">
                                <text>{{ item.name }}</text>
                            </view>
                        </uni-col>
                    </uni-row>
                    <button @click="clickSelectAttender1" class="btn-add">添加交班人</button>
                </uni-forms-item>
                <uni-forms-item label="接班人" required>
                    <uni-row v-if="attenders2.length != 0">
                        <uni-col :span="8" v-for="(item, idx) in attenders2" :key="idx">
                            <view class="user-bg">
                                <text>{{ item.name }}</text>
                            </view>
                        </uni-col>
                    </uni-row>
                    <button @click="clickSelectAttender2" class="btn-add">添加接班人</button>
                </uni-forms-item>
                <uni-forms-item label="值班内容记录">
                    <uni-easyinput type="textarea" v-model="liuzhuanForm.watchContentRecord" />
                </uni-forms-item>

                <uni-forms-item label="事件处理结果">
                    <uni-easyinput type="textarea" v-model="liuzhuanForm.watchResult" />
                </uni-forms-item>
                <view style="font-size:14px;margin-bottom:15px">值班要求</view>
                <view class="tips">
                    <view>
                        1.值班人员值班期间必须24小时在岗，保持电话通畅，遇到重大事情，必须报告上级领导并做好临时处理措施，积极处置。
                    </view>
                    <view>
                        2.值班期间，不得脱岗，认真值班。
                    </view>
                    <view>3.值班人员要做好值班记录，重要事情要记载，做好交接班等有关工作。</view>
                    <view>4.值班人员受理来电，须详细登记来电信息，包括来电时间、来电人姓名、联系方式和来电内容。</view>
                    <view>5.值班人员因特殊情况调整换班的需提前向办公室报备。</view>
                </view>


                <view style="padding-top: 30px;"></view>
                <button type="primary" @click="clickApply">提交</button>
            </uni-forms>
        </view>

        <!-- ------------------------------------------------ -->
        <view v-if="currentIndex === 1">
            <view class="tops">
                <view>
                    <button @click="clickSelectOne" class="btn-add" v-if="users.length != 0">{{ users[0].name }}</button>
                </view>
                <view style="margin-bottom:15px">
                    <button @click="clickSelectOne" class="btn-add" v-if="users.length == 0">{{ '选择查询人员' }}</button>
                </view>
                <picker mode="date" fields="month" :value="keyword" @change="search" style="height: 18px;" start="1990-01"
                    end="2050-09">
                    <uni-row>
                        <uni-col :span="12">
                            <view class="text-left">查询日期</view>
                        </uni-col>
                        <uni-col :span="12">
                            <view class="text-right">{{ keyword }}
                                <uni-icons type="calendar-filled"> </uni-icons>
                            </view>
                        </uni-col>
                    </uni-row>
                </picker>
            </view>
            <view v-for="(item, idx) in applyRecord" style="padding-bottom: 10px;" :key="idx">
                <!-- {{item}} -->
                <view class="card" @click="seeDetail(idx)">
                    <view class="card-body">
                        <view>值班内容：{{ item.watchContentRecord }}</view>
                    </view>
                    <view class="card-footer">
                        <uni-row>
                            <uni-col :span="12">
                                <view class="card-footer-left">{{ item.createBy }}</view>
                            </uni-col>
                            <uni-col :span="12">
                                <view class="card-footer-right">{{ getFormatedTimeStr(item.createTime, "YYYY-MM-DD HH:mm:ss") }}
                                </view>
                            </uni-col>
                        </uni-row>
                    </view>
                </view>
            </view>
            <uni-load-more :status="moreStatus"></uni-load-more>
        </view>
    </view>
</template>
    
<script>
import moment from "moment";
import { websock } from "../../net/websock";
import { addzhibanjilu, getzhibanjiluList } from "../../net/zhibanjilu";
import { uploadconfig3 } from "../../const";
import { quchongAuditors } from "../../utils/util";

export default {
    data() {
        return {
            // 上传参数部分没有事情不要乱动
            uploadconfig3,
            option: {
                url: uploadconfig3.url,
                name: "file",
                header: { Authorization: uni.getStorageSync("token"), platform: 'APP' },
                formData: {}
            },
            total: 1, //当前页
            users: [],
            pageSize: 10,
            pageNum: 1,
            formats: uploadconfig3.formats,
            instantly: uploadconfig3.instantly,
            size: uploadconfig3.size,
            items: ["发起提交", "历史数据"],
            currentIndex: 0,
            typeIndex: 0,
            attenders: [],//陪同人员
            attenders1: [],//陪同人员
            attenders2: [],//陪同人员
            userInfo: '',
            moreStatus: "more",
            applyRecord: [],
            keyword: "",
            suffix: "",
            files: new Map(),
            liuzhuanForm: {
                watchTime: '',//值班日期
                watchId: "",//值班人
                successorId: "",//接班人
                handoverId: "",//交班人
                watchContentRecord: "",//值班内容记录
                watchResult: '',//事件处理结果
                auditors: []
            }
        };
    },
    async onLoad() {
        try {
            this.userInfo = await websock.getUserInfo();
            console.log("user info", this.userInfo);
        } catch (err) {
            console.error(err);
        }
    },
    async onReady() {
        try {
            this.userInfo = await websock.getUserInfo();
        } catch (e) {
            uni.showToast({
                title: e.message
            });
        }
        // this.getNewestRecord();
    },
    // 下拉刷新，获取最新的数据
    onPullDownRefresh() {
        if (this.currentIndex == 0) {
            uni.stopPullDownRefresh();
        } else {
            this.pageNum = 1;
            this.applyRecord = [];
            this.getNewestRecord();
        }
    },
    // 上拉刷新，获取历史数据
    onReachBottom() {
        if (this.currentIndex == 1) {
            if (this.moreStatus == "more") {
                uni.showLoading({
                    title: "加载中"
                });
                this.pageNum += 1;
                this.getOlderRecord();
            }
        }
    },
    methods: {
        roomNameStr() {
            return this.gzcType[this.typeIndex] || ''
        },
        //选择查询人员
        clickSelectOne() {
            uni.navigateTo({
                url:
                    "/pages/common/contactSelect?selectedUsers=" +
                    JSON.stringify(this.users || []) +
                    "&isSingle=1",
                events: {
                    contactList: data => {
                        console.log("select peitong", data);
                        this.users = data.contactList;
                        this.pageNum = 1
                        this.pageSize = 10
                        this.applyRecord = [];
                        this.getNewestRecord();
                    }
                }
            });
        },
        //选择值班人员
        clickSelectAttender() {
            uni.navigateTo({
                url: '/pages/common/contactSelect?selectedUsers=' + JSON.stringify(this.attenders || []),
                events: {
                    contactList: data => {
                        console.log('select auditor', data)
                        this.attenders = data.contactList
                        let arr = []
                        data.contactList.forEach(item => {
                            arr.push(item.uid)
                        })
                        console.log(arr.join(','));
                        this.liuzhuanForm.watchId = arr.join(',')
                    }
                }
            })
        },
        //选择交班人员
        clickSelectAttender1() {
            uni.navigateTo({
                url: '/pages/common/contactSelect?selectedUsers=' + JSON.stringify(this.attenders1 || []),
                events: {
                    contactList: data => {
                        console.log('select auditor', data)
                        this.attenders1 = data.contactList
                        let arr = []
                        data.contactList.forEach(item => {
                            arr.push(item.uid)
                        })
                        console.log(arr.join(','));
                        this.liuzhuanForm.handoverId = arr.join(',')
                    }
                }
            })
        },
        //选择接班人员
        clickSelectAttender2() {
            uni.navigateTo({
                url: '/pages/common/contactSelect?selectedUsers=' + JSON.stringify(this.attenders2 || []),
                events: {
                    contactList: data => {
                        console.log('select auditor', data)
                        this.attenders2 = data.contactList
                        let arr = []
                        data.contactList.forEach(item => {
                            arr.push(item.uid)
                        })
                        console.log(arr.join(','));
                        this.liuzhuanForm.successorId = arr.join(',')
                    }
                }
            })
        },
        // 获取最新的通知
        async getNewestRecord() {
            try {
                if (this.applyRecord.length == 0) {
                    let res = await getzhibanjiluList({
                        userId: this.users.length !== 0 ? this.users[0].uid : '',
                        pageNum: this.pageNum,
                        pageSize: 10,
                        watchTime: this.keyword
                    });
                    uni.hideLoading();
                    uni.stopPullDownRefresh();
                    this.total = res.total;
                    this.applyRecord = [...res.data, ...this.applyRecord];
                } else {
                    let res = await getzhibanjiluList({
                        userId: this.users.length !== 0 ? this.users[0].uid : '',
                        pageNum: this.pageNum,
                        pageSize: 10,
                        watchTime: this.keyword
                    });
                    uni.hideLoading();
                    uni.stopPullDownRefresh();
                    this.applyRecord = [...res.data, ...this.applyRecord];
                }
            } catch (e) {
                console.log(e);
            }
        },
        // 穿刺一击让他们的遮罩层消失
        chuanci() {
            this.$refs.lsjUpload && this.$refs.lsjUpload.hide();
        },
        // 穿刺一击让他们的遮罩层消失
        chuanci2() {
            this.$refs.lsjUpload && this.$refs.lsjUpload.show();
            this.$forceUpdate();
        },
        // 获取老的数据
        async getOlderRecord() {
            this.moreStatus = "loading";
            try {
                if (this.applyRecord.length == 0) {
                    let res = await getzhibanjiluList({
                        userId: this.users.length !== 0 ? this.users[0].uid : '',
                        pageNum: this.pageNum,
                        pageSize: this.pageSize,
                        watchTime: this.keyword
                    });

                    this.applyRecord = this.applyRecord.concat(res.data);
                    if (res.data.length < 10) {
                        this.moreStatus = "noMore";
                    } else {
                        this.moreStatus = "more";
                    }
                } else {
                    let res = await getzhibanjiluList({
                        userId: this.users.length !== 0 ? this.users[0].uid : '',
                        pageNum: this.pageNum,
                        pageSize: this.pageSize,
                        watchTime: this.keyword
                    });

                    this.applyRecord = this.applyRecord.concat(res.data);
                    if (res.data.length < 10) {
                        this.moreStatus = "noMore";
                    } else {
                        this.moreStatus = "more";
                    }
                }
            } catch (e) {
                uni.showToast({
                    title: e.message
                });
            }
        },

        onClickItem(e) {
            console.log(e);
            if (this.currentIndex !== e.currentIndex) {
                this.currentIndex = e.currentIndex;
                if (this.currentIndex == 1) {
                    this.applyRecord = [];
                    this.getNewestRecord();
                }
            }
        },
        // 获取格式化时间字符串
        getFormatedTimeStr(stamp, str = "MM-DD HH:mm:ss") {
            return moment(stamp).format(str);
        },
        async clickApply() {
            if (!this.liuzhuanForm.watchId)
                return uni.showToast({
                    title: "请选择值班人员",
                    icon: "none"
                });
            if (!this.liuzhuanForm.watchTime)
                return uni.showToast({
                    title: "请选择值班时间",
                    icon: "none"
                });
            if (!this.liuzhuanForm.handoverId)
                return uni.showToast({
                    title: "请选择交班人员",
                    icon: "none"
                });
            if (!this.liuzhuanForm.successorId)
                return uni.showToast({
                    title: `请选择接班人员`,
                    icon: "none"
                });
            const tbWatchRecord = {
                userId: this.userInfo.uid,
                createBy: this.userInfo.name,
                deptId: this.userInfo.department,
                watchId: this.liuzhuanForm.watchId,
                handoverId: this.liuzhuanForm.handoverId,
                successorId: this.liuzhuanForm.successorId,
                watchTime: this.liuzhuanForm.watchTime,
                watchContentRecord: this.liuzhuanForm.watchContentRecord,
                watchResult: this.liuzhuanForm.watchResult,
            };
            console.log(tbWatchRecord);
            try {
                await addzhibanjilu(tbWatchRecord);
                setTimeout(
                    () =>
                        // uni.navigateBack({
                        //     delta: 1
                        // }),
                        uni.showToast({
                            title: "操作成功",
                            icon: "success"
                        }),
                    1000
                );
                this.liuzhuanForm = {
                    watchTime: '',//值班日期
                    watchId: "",//值班人
                    successorId: "",//接班人
                    handoverId: "",//交班人
                    watchContentRecord: "",//值班内容记录
                    watchResult: '',//事件处理结果
                    auditors: []
                };

                this.currentIndex = 1;
                this.applyRecord = [];
                this.getNewestRecord();
            } catch (err) {
                uni.showToast({
                    title: err.message || "error"
                });
            }

        },
        seeDetail(idx) {
            console.log(idx);
            uni.navigateTo({
                url: `/pages/task/zhibanjiluDetail?content=${this.applyRecord[idx].id}`
            });
        },
        search(e) {
            this.keyword = e.detail.value
            this.applyRecord = [];
            this.pageNum = 1
            this.pageSize = 10
            this.getNewestRecord();
        }
    }
};
</script>
    
<style>
@import "../common/common.css";

/* 封面上传控件 */
::v-deep .file-picker__box {
    position: absolute !important;
    right: 0 !important;
    width: 200rpx !important;
    height: 132rpx !important;
}

::v-deep .file-picker__box-content {
    border: none !important;
}

.tops {
    margin: 15px 0
}

.text-right {
    font-size: 14px;
    padding-right: 10px;
    text-align: right;
}

.text-left {
    font-size: 14px;
    padding-left: 10px;
    text-align: left;
}
</style>
    